define(["jquery", "juicer", "core/util", "hc", "core/personCfg"]
	, function($, j, util, hc, cfg) {

	//初始化模板
	var tplSession = j(document.getElementById("tpl-session-panel").innerHTML);
	var tplMessage = j(document.getElementById("tpl-message-li").innerHTML);
	var tplSessionIcon = j(document.getElementById("tpl-session-icon").innerHTML);
	var tplSessionMenu = j(document.getElementById("tpl-session-menu").innerHTML);
	var $menuBC = $("#menuBarContainer");
	
	var ToolbarPlugins={
	};

	//窗口缓存
	var WinCache = new Map();
	var ShowWin = [];
	var CurrentWin = null;
	var CurrentSession=null;

	var Tools = {
		
		initMenuPLugin:function(keyId){
			var _this=this,
				data=window.UserPlugins,
				$toolbar=$("#toolbar-"+keyId);
			data.forEach(function(item, index, _array) {
				if(item.luncher=="DIALOGMENU"){
					$toolbar.append(tplSessionMenu.render(item));
					if(!ToolbarPlugins[item.uuid]){
						require([item.module], function(_) {
							ToolbarPlugins[item.uuid] = _;
						})						
					}
				}
				_this.initMenuEvent(keyId);
			})
			$.parser.parse($toolbar);
		},
		
		initMenuEvent:function(keyId){
			var $menus=$("#toolbar-"+keyId+" a");
			$menus.on("click",function(){
				var _this=$(this),
					_type=_this.attr("mtype"),
					_pid=_this.attr("pid");
				if(_type=="plugin"){
					try{
						ToolbarPlugins[_pid].run(CurrentSession);
					}catch(e){
						console.error(e);
					}
				}
			})
		},

		saveFile: function(data, filename) {
			var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
			save_link.href = data;
			save_link.download = filename;
			var event = document.createEvent('MouseEvents');
			event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
			save_link.dispatchEvent(event);
		},

		/**
		 * 测试版功能、用于技术测试 
		 * @param {Object} id
		 */
		saveDialogImage: function(id) {
			id = "dialog-wrap-" + id;
			hc(document.getElementById(id)).then(function(canvas) {
				var data = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream;");
				Tools.saveFile(data, new Date().getTime() + ".png");
			});
		},

		close: function(keyId) {
			WinCache.get(keyId).window("close");
		}

	}

	var View = {

		/**
		 * 创建会话面版
		 * @param {Object} param
		 */
		createSessionViewWindow: function(param, callback) {
			var keyId = param.keyId,
				sessionId = param.sessionId;
			var $div = $("<div/>").appendTo($("body"));
			$div.window({
				width: 950,
				height: 500,
				shadow:false,
				title: param.user.name || "【匿名用户】",
				content: tplSession.render(param),
				openAnimation: "slide",
				onBeforeOpen: function() {
					WinCache.forEach(function(value, key, _map) {
						value.window("minimize");
					})
					if (!WinCache.get(keyId)) {
						WinCache.set(keyId, $div);
						View.initView($(this), keyId);
						
						var p=tplMessage.render({
							user:param.user,
							source:0,
							type:"text",
							content:"Hi,谢谢你响应我的服务请求!请等待我回复哦..."
						});
						$("#"+keyId).append(p);
						
						return false;
					}
					return true;
				},
				onOpen: function() {
					CurrentWin = keyId;
					CurrentSession=param;
					callback && callback(keyId, sessionId);
				},
				onClose: function() {
					closeSession(keyId);
					$div.window("destroy", true);
				},
				onMinimize: function() {
					CurrentWin = null;
				}

			});
			var c = $div.window("options");
			$div.window("move", {
				top: 10
			})
		},

		/**
		 * 创建会话图标 
		 * @param {Object} session 会话对象
		 */
		createSessionIcon: function(session) {
			var dom = tplSessionIcon.render(session);
			$menuBC.append(dom);
		},

		/**
		 * 移除会话图标
		 * @param {Object} keyId
		 */
		removeSessionIcon: function(keyId) {
			$("#menu-icon-" + keyId).remove();
		},

		/**
		 * 最小化视图
		 */
		minView: function(session) {

		},
		
		initView: function($dom, keyId) {
			var _$area = $dom.find("textarea"),
				$commit=$("#base-info-"+keyId+" a[name='commit']"),
				$readSessionBtn=$("#business-info-"+keyId+" label[name='readSession']"),
				$sessionTab=$("#tab-"+keyId),
				_baseInfo=new Map();
			
			View.initToolbar($dom, keyId);
			Tools.initMenuPLugin(keyId);
			_$area.keydown(function(e) {
				var _code = e.keyCode,
					_val = $(this).val();
				if (_code == "13" && _val) {
					e.preventDefault();
					reply(keyId, {
						type: "text",
						content: _val
					});
					$(this).val("");
				}
			})
			
			$readSessionBtn.on("click",function(){
				var _this=$(this),
					sid=_this.attr("sid");
				
				$sessionTab.tabs("add",{
					title:"上一次会话详情",
					content:j(document.getElementById("tpl-session-detail").innerHTML).render({sessionId:sid}),
					onOpen:function(){
					}
				})
				setTimeout(function(){
					_this.replaceWith("正在查看");
					loadMessageBySessionId(sid,function(_){
						$("#last-session-history-" + sid).append(tplMessage.render(_));
					})
				},1000)
			})
			$commit.on("click",function(){
				var id=$(this).attr("cid");
				util.post("/session/update/customer/"+id+"/"+keyId,util.map2Obj(_baseInfo),function(data){
					if(data.code==0){
						util.toast("操作成功");
						$commit.hide();
					}else{
						util.toast("操作失败","error");
					}
				})
			})
			
			$("#base-info-"+keyId+" input").on("blur",function(){
				var _this=$(this);
				if(_this.val()!==_this.attr("oval")){
					_baseInfo.set(_this.attr("name"),_this.val());
				}else{
					_baseInfo.delete(_this.attr("name"));					
				}
				if(_baseInfo.size>0){
					$commit.show();
				}else{
					$commit.hide();
				}
			})
			
			initDragImage(_$area, keyId);
		},

		/**
		 * 初始化工具栏 菜单事件 
		 * @param {Object} $dom
		 * @param {Object} keyId
		 */
		initToolbar: function($dom, keyId) {
			$dom.find("a[name='print']").on("click", function() {
				Tools.saveDialogImage(keyId);
			})
			$dom.find("a[name='close']").on("click", function() {
				Tools.close(keyId);
			})
		}

	}

	//初始化
	function init() {

	}

	//接收一个会话
	function acceptSession() {

	}

	/**
	 * 关闭会话
	 * @param {Object} keyId 会话KeyID
	 */
	function closeSession(keyId) {
		util.get("/session/close/" + keyId, function() {
			util.toast("会话已关闭");
		});
		View.removeSessionIcon(keyId);
		WinCache.delete(keyId);
		//	ShowWin.splice(ShowWin.indexOf(keyId), 1);
	}

	//接收一条消息
	function acceptMessage(message) {
		var keyId = message.keyId;
		message.user.image = message.user.image || "res/images/user-header.png";
		message.user.name = message.user.name || "[匿名用户]";
		$("#" + keyId).append(tplMessage.render(message));
		if (CurrentWin != keyId) {
			if ($("#menu-icon-" + keyId)) {
				var e = $("#menu-icon-" + keyId + " .edge");
				$("#menu-icon-" + keyId).addClass("animated flash");
				e.html(parseInt(e.text()) + 1).show();
			}
		}
		$("#" + keyId).parent().scrollTop(99999);
	}

	//回复一条消息
	function reply(keyId, data) {
		data.keyId = keyId;
		data.user = {
			name: cfg.query("nickname"),
			image: "res/images/agent-header.png"
		};
		data.source = 1;
		var d = $(tplMessage.render(data)).appendTo($("ul#" + keyId));
		util.post("/message/send", data, function(result) {
			if (result.code) {
				d.find(".content").addClass("errorMessage");
				d.find(".time").html("<nobr style='color:red;'>[发送失败]</nobr>");
			}
		}, function() {
			d.find(".content").addClass("errorMessage");
			d.find(".time").html("<nobr style='color:red;'>[网络错误]</nobr>");
		})
		$("#" + keyId).parent().scrollTop(99999);

	}


	function initDragImage($dom, keyId) {

		$dom.on("drop", function(event) {
			event.preventDefault();
			var $bar = $dom.next().find("div");

			var files = event.originalEvent.dataTransfer.files;
			if (files.length > 0) {
				if (files[0].type.indexOf('image') === -1) {
					util.toast("请选择图片格式文件发送...", "error");
					return false;
				}
				var _file = files[0];
				var fd = new FormData();
				fd.append("ufile", _file);
				var xhr = new XMLHttpRequest();
				xhr.open("post", "/upload", true);
				xhr.upload.addEventListener("progress", function(e) {
					//计算上传进度
					if (e.lengthComputable) {
						var percentage = Math.round((e.loaded * 100) / e.total);
						$bar.css("width", percentage + "%");
					}
				}, false);
				xhr.addEventListener("load", function() {
					var a = JSON.parse(xhr.responseText);
					var path = a.content;
					reply(keyId, {
						type: "image",
						content: path
					});
				});
				xhr.send(fd);
			}
		})
	}


	function setVoice() {
		var d = '<video style="display:none" preload="preload"><source src="res/voice/default.mp3" type="audio/mp3"></video>';
		$(d).appendTo($("body"));
		return $(d)[0];
	}
	
	function loadMessageBySessionId(sessionId,callback){
		util.get("/message/query/" + sessionId, function(res) {
				if (res.code == 0 && res.des.length) {
					res.des.forEach(function(val) {
						var _ = val,
							_img="";
						if(val.source==1){
							_img=val.image||"res/images/agent-header.png";
						}else if(val.source==0){
							_img=val.image||"res/images/user-header.png";
						}
						_.user = {
								image: _img,
								name: val.name
							}	
						callback && callback(_);
					})
				}
			})
	}

	return {

		voice: null,

		init: function(clientId) {
			$("body").on("click", function(e) {
				var _pe = e.target.parentElement;
				if (_pe && _pe.className.indexOf("menuItem") == 0) {
					var id = _pe.getAttribute("mid");
					WinCache.get(id).window("open");
					var e = $("#menu-icon-" + id + " .edge");
					e.html(0).hide();
					$("#menu-icon-" + id).removeClass("animated flash");
				}
			});
			this.voice = setVoice();

			this.unfinish(clientId);
		},

		/**
		 * 加载未完成的会话
		 * @alias 典型的异步回掉地狱模式
		 * @param {Object} clientId
		 */
		unfinish: function(clientId) {
			util.get("/session/unfinish/" + clientId, function(data) {
				if (data.code == 0 && data.des.length) {
					data.des.forEach(function(val, index, _array) {
						View.createSessionIcon(val);
						View.createSessionViewWindow(val, function(keyId, sessionId) {
							loadMessageBySessionId(sessionId,function(_){
								$("#" + keyId).append(tplMessage.render(_));
							})
						})
					})
				}
			})

		},

		accept: function(type, param) {
			if (type == "session") {
				if (cfg.check("isVoice", "开启")) {
					this.voice.play();
				}
				View.createSessionIcon(param);
				View.createSessionViewWindow(param);
			} else if (type == "message") {
				if (cfg.check("isVoice", "开启")) {
					this.voice.play();
				}
				acceptMessage(param);
			}
		}
	}
})